package com.bifang.core.dict.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.common.vo.BasePageVO;
import com.bifang.common.vo.OrderVO;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.util.ClassUtils;

/** 通用工具类 */
public class CommonUtil {
    // 首字母转小写
    public static String toLowerCaseFirstOne(String s) {
        if (Character.isLowerCase(s.charAt(0))) return s;
        else
            return (new StringBuilder())
                    .append(Character.toLowerCase(s.charAt(0)))
                    .append(s.substring(1))
                    .toString();
    }
    // 首字母转大写
    public static String toUpperCaseFirstOne(String s) {
        if (Character.isUpperCase(s.charAt(0))) return s;
        else
            return (new StringBuilder())
                    .append(Character.toUpperCase(s.charAt(0)))
                    .append(s.substring(1))
                    .toString();
    }

    public static Class getClass(String tableName) {
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();

        try {
            Class<?> clazz = null;
            boolean flag = false;
            String patternJW =
                    ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
                            + ClassUtils.convertClassNameToResourcePath("com.jwsoft")
                            + "/**/model/**/*.class";
            Resource[] resourcesJW = resourcePatternResolver.getResources(patternJW);
            MetadataReaderFactory readerfactoryJW =
                    new CachingMetadataReaderFactory(resourcePatternResolver);
            for (Resource resource : resourcesJW) {
                MetadataReader reader = readerfactoryJW.getMetadataReader(resource);
                // 扫描到的class
                String classname = reader.getClassMetadata().getClassName();
                clazz = Class.forName(classname);
                // 判断是否有指定主解
                TableName anno = clazz.getAnnotation(TableName.class);
                if (anno != null) {
                    String value = anno.value().toUpperCase();
                    if (value.equals(tableName.toUpperCase())) {
                        flag = true;
                        break;
                    }
                }
            }
            if (flag) {
                return clazz;
            }
            String pattern =
                    ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
                            + ClassUtils.convertClassNameToResourcePath("com.bifang")
                            + "/**/model/**/*.class";
            Resource[] resources = resourcePatternResolver.getResources(pattern);
            MetadataReaderFactory readerfactory =
                    new CachingMetadataReaderFactory(resourcePatternResolver);

            for (Resource resource : resources) {
                MetadataReader reader = readerfactory.getMetadataReader(resource);
                // 扫描到的class
                String classname = reader.getClassMetadata().getClassName();
                clazz = Class.forName(classname);
                // 判断是否有指定主解
                TableName anno = clazz.getAnnotation(TableName.class);
                if (anno != null) {
                    String value = anno.value().toUpperCase();
                    if (value.equals(tableName.toUpperCase())) {
                        flag = true;
                        break;
                    }
                }
            }

            if (flag) {
                return clazz;
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getFieldName(Class beanClass, String name) {
        try {
            Field field = beanClass.getDeclaredField(name);
            if (field.isAnnotationPresent(TableId.class)) {
                TableId tableId = field.getAnnotation(TableId.class);
                return tableId.value();
            }
            if (field.isAnnotationPresent(TableField.class)) {
                TableField tableField = field.getAnnotation(TableField.class);
                return tableField.value();
            }

        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static QueryWrapper<?> pageOrder(BasePageVO vo, QueryWrapper<?> qw) {
        if (ObjectUtil.isNotNull(vo.getOrderVOList())) {
            List<OrderVO> orderVOList = vo.getOrderVOList();
            List<String> checkList = Arrays.asList("userName", "fullName", "nikeName");
            orderVOList.forEach(
                    item -> {
                        if ("asc".equals(item.getOrder())) {
                            if (checkList.contains(item.getProperty())) {
                                qw.orderByAsc(StrUtil.toUnderlineCase(item.getProperty()));
                            } else {
                                qw.orderByAsc(
                                        StrUtil.endWith(item.getProperty(), "Name")
                                                ? StrUtil.removeAll(item.getProperty(), "Name")
                                                : StrUtil.toUnderlineCase(item.getProperty()));
                            }

                        } else if ("desc".equals(item.getOrder())) {
                            if (checkList.contains(item.getProperty())) {
                                qw.orderByAsc(StrUtil.toUnderlineCase(item.getProperty()));
                            } else {
                                qw.orderByDesc(
                                        StrUtil.endWith(item.getProperty(), "Name")
                                                ? StrUtil.removeAll(item.getProperty(), "Name")
                                                : StrUtil.toUnderlineCase(item.getProperty()));
                            }
                        }
                    });
        }
        return qw;
    }
}
